#include<iostream>
#include<string>
#include<websocketpp/server.hpp>
#include<websocketpp/config/asio_no_tls.hpp>

typedef websocketpp::server<websocketpp::config::asio> wsserver_t;
void print(const std::string& str)
{
    std::cout << str << std::endl;
}
void wshttp_callback(wsserver_t* server, websocketpp::connection_hdl hdl)
{
    //给客户端返回一个hellow world的页面
    wsserver_t::connection_ptr conn = server->get_con_from_hdl(hdl);
    std::cout << "body: " << conn->get_request_body() << std::endl;
    websocketpp::http::parser::request request = conn->get_request();
    std::cout << "method: " << request.get_method() << std::endl;
    std::cout << "uri: " << request.get_uri() << std::endl;
    std::string body = "<html><body><h1>hellow world!<h1/><body/><html/>";
    conn->set_body(body);
    conn->set_status(websocketpp::http::status_code::ok);
    server->set_timer(500000, std::bind(print, "定时器已销毁！"));
}
void wsopen_callback(wsserver_t* server, websocketpp::connection_hdl hdl)
{
    std::cout << "websocket握手成功" << std::endl;   
}
void wsclose_callback(wsserver_t* server, websocketpp::connection_hdl hdl)
{
    std::cout << "websocket连接断开" << std::endl;   
}
void wsmessage_callback(wsserver_t* server, websocketpp::connection_hdl hdl, wsserver_t::message_ptr message)
{
    wsserver_t::connection_ptr conn = server->get_con_from_hdl(hdl);
    std::cout << "wsmessage: " << message->get_payload() << std::endl;
    std::string rsp = "client say: " + message->get_payload();
    conn->send(rsp, websocketpp::frame::opcode::text);
}
int main()
{
    //1.实例化server对象
    wsserver_t wssrv;
    //2.设置日志输出等级
    wssrv.set_access_channels(websocketpp::log::alevel::none);
    //3.初始化asio框架中的调度器
    wssrv.init_asio();
    wssrv.set_reuse_addr(true);
    //4.设置业务处理回调函数
    wssrv.set_http_handler(std::bind(wshttp_callback, &wssrv, std::placeholders::_1));
    wssrv.set_open_handler(std::bind(wsopen_callback, &wssrv, std::placeholders::_1));
    wssrv.set_close_handler(std::bind(wsclose_callback, &wssrv, std::placeholders::_1));
    wssrv.set_message_handler(std::bind(wsmessage_callback, &wssrv, std::placeholders::_1, std::placeholders::_2));
    //5.设置服务器监听端口
    wssrv.listen(8085);
    //6.开始获取新建连接
    wssrv.start_accept();
    //7.启动服务器
    wssrv.run();
    return 0;
}